package com.aduerr.v1shouyin.mvp.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.OrderGetPosOrderLEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.print.PrinterWrapper;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2021/3/16 11:31
 * @change
 * @chang time
 * @class describe
 */

public class RefundMultiRecordActivity extends AppCompatActivity {
    @BindView(R.id.rv_refund_record)
    RecyclerView mRv;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private OrderGetPosOrderLEntity.DataBean.ListBean data;
    BaseQuickAdapter<OrderGetPosOrderLEntity.DataBean.ListBean.OrderItemRefund,
            BaseViewHolder> adapter;
    List<OrderGetPosOrderLEntity.DataBean.ListBean.OrderItemRefund> list =
            new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refund_multi_record);
        ButterKnife.bind(this);
        mTvTitle.setText("退款记录");
        mTvTitle.setVisibility(View.VISIBLE);
        initView();

    }

    public void initView() {
        data = (OrderGetPosOrderLEntity.DataBean.ListBean) getIntent().getSerializableExtra("refundRecord");
        list.addAll(data.getOrderItemRefundList());
        setAdapter();
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                String orderId = data.getOrderid();
                getDataList(orderId);
                refreshlayout.finishRefresh(2000);
            }
        });
    }


    @OnClick({R.id.img_back})
    public void onClick(){
        finish();
    }

    public void setAdapter() {
        if(adapter == null) {
            adapter =
                    new BaseQuickAdapter<OrderGetPosOrderLEntity.DataBean.ListBean.OrderItemRefund, BaseViewHolder>(R.layout.item_refund_multi_record, list) {
                        @Override
                        protected void convert(BaseViewHolder helper,
                                               OrderGetPosOrderLEntity.DataBean.ListBean.OrderItemRefund item) {
                            helper.setText(R.id.item_refund_time, item.getRefundTime());
                            helper.setText(R.id.item_refund_order_no,
                                    item.getRefundOrderID());
                            helper.setText(R.id.item_refund_amount,
                                    item.getRefundAmount() + "");
                            helper.setText(R.id.item_refund_state,
                                    item.getRefundStatus());
                            helper.setText(R.id.item_refund_people,
                                    item.getRefundUserName());
                            helper.setText(R.id.item_refund_remark,
                                    item.getRefundReason());
                            helper.addOnClickListener(R.id.item_ll_refund);
                        }
                    };
            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view,
                                             int position) {
                    int printPage =
                            (int) SharedPreferencesUtils.getParam(RefundMultiRecordActivity.this,
                            "printpage", 1);
                    if(printPage==0){
                        ToastUtils.showToast(RefundMultiRecordActivity.this, "打印张数设置为不打印,请先设置打印张数!!");
                    }else{
                        PrinterWrapper.printMultiRefundOrderDetail(data, position, printPage,false);
                    }

                }
            });
            mRv.setHasFixedSize(true);
            mRv.setNestedScrollingEnabled(false);
            LinearLayoutManager manager = new LinearLayoutManager(this,
                    LinearLayoutManager.VERTICAL, false);

            mRv.setLayoutManager(manager);
            mRv.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }


    /**
     * 查询列表
     *
     * @param orderId 订单ID
     */
    private void getDataList(String orderId) {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderId", orderId);
        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderGetPosOrderLEntity>() {

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull OrderGetPosOrderLEntity entity) {
                        int success = entity.getSuccess();
                        if(success == 1) {
                            data = entity.getData().get(0).getList().get(0);
                            list.clear();
                            list.addAll(data.getOrderItemRefundList());
                            setAdapter();

                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(RefundMultiRecordActivity.this, "autologin");
                            SharedPreferencesUtils.remove(RefundMultiRecordActivity.this, "remberpassword");
                            startActivity(new Intent(RefundMultiRecordActivity.this,
                                    BangGuidActivity.class));
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(entity.getErrMsg());
                            SharedPreferencesUtils.remove(RefundMultiRecordActivity.this, "autologin");
                            SharedPreferencesUtils.remove(RefundMultiRecordActivity.this, "remberpassword");
                            startActivity(new Intent(RefundMultiRecordActivity.this,
                                    LoginActivity.class));
                        } else {
                            ToastUtils.showToast(RefundMultiRecordActivity.this,
                                    entity.getErrMsg() + "");
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(RefundMultiRecordActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(RefundMultiRecordActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());
                            Toast.makeText(RefundMultiRecordActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
